package com.zxy.fmmall.controller;

import com.github.wxpay.sdk.WXPayUtil;
import com.zxy.fmmall.service.OrdersService;
import com.zxy.fmmall.websocket.WebSocketService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("pay")
@Api("微信支付回调接口")
@CrossOrigin
public class PayController {
    @Autowired
    private OrdersService ordersService;
    @ApiOperation("微信支付成功回调接口")
    @PostMapping("/callback")
    public String success(HttpServletRequest request) throws Exception {
        ServletInputStream is = request.getInputStream();
        byte[] bytes = new byte[1024];
        int len = -1;
        StringBuilder stringBuilder = new StringBuilder();
        while ((len = is.read(bytes)) != -1){
            stringBuilder.append(new String(bytes,0,len));
        }

        String s = stringBuilder.toString();
        //使用帮助类 将xml接口的字符转换成map
//        不是json格式不能用json转
        Map<String, String> map = WXPayUtil.xmlToMap(s);
        if(map != null && "success".equalsIgnoreCase(map.get("result_code"))){
            // 支付成功
            // 修改订单状态为“代发货/已支付/
            String orderId = map.get("out_trade_no");
            int i = ordersService.updateOrderStatus(orderId,"2");
            WebSocketService.sendMessage(orderId,"1");
            if (i > 0){
                //响应微信支付平台  否则微信一直响应
                HashMap<String, String> resp = new HashMap<>();
                resp.put("return_code","success");
                resp.put("return_msg","OK");
                resp.put("appid",map.get("appid"));
                return WXPayUtil.mapToXml(resp);
            }
        }
        return null;
    }
}
